#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <strings.h>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

namespace Server
{
    using namespace std;

    static const string defaultIp = "0.0.0.0";
    static const int gnum = 1024;

    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR,
        OPEN_ERR
    };
     
    typedef function<void(int,string,uint16_t,string)> func_t;

    class udpServer
    {
    public:
        udpServer(const func_t& cb, const uint16_t &port, const string &ip = defaultIp)
            : _callback(cb),_port(port), _ip(defaultIp)
        {
        }

        void initServer()
        {
            // 1.创建socket
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                cerr << "socket error: " << errno << " : " << strerror(errno) << endl;
                exit(SOCKET_ERR);
            }
            cout << "socket success: " << " : " << _sockfd << endl;

            // 2.绑定port,ip
            // 未来服务器要明确的port，不能随意改变
            struct sockaddr_in local; // 在栈上（用户）定义了一个变量
            bzero(&local, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);                  // 给别人发消息，自己的ip和port也要发送给对方，转换大小端
            local.sin_addr.s_addr = inet_addr(_ip.c_str()); // 1.string->uint32_t 2.htonl();  ->  inet_addr
            //local.sin_addr.s_addr = INADDR_ANY;             // 任意地址bind，服务器的真实写法

            int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
            if (n == -1)
            {
                cerr << "socket error: " << errno << " : " << strerror(errno) << endl;
                exit(BIND_ERR);
            }
        }

        void start()
        {
            // 服务器的本质就是一个死循环
            char buffer[gnum];
            for (;;)
            {
                // 读数据
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer, &len);
                // 1.数据是什么 2.谁发的
                if(s > 0)
                {
                    buffer[s] = 0; // 处理最后一个\0
                    string clientip = inet_ntoa(peer.sin_addr);     //1.网络序列 2.int->点分十进制
                    uint16_t clientport = ntohs(peer.sin_port);
                    string messages = buffer;

                    cout << clientip << "[" << clientport << "]# " << messages << endl;
                    // 读完数据后就要对数据做处理
                    _callback(_sockfd, clientip, clientport, messages);
                }
            }
        }

        ~udpServer()
        {
        }

    private:
        uint16_t _port;
        string _ip;
        int _sockfd;
        func_t _callback;
    };
}